package com.nothing.service.run;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.nothing.controller.TakeFaceController;
import com.nothing.controller.WebCamPreviewController;
import com.nothing.service.UserFaceInfoService;
import com.nothing.util.ExcutorUtil;
import com.nothing.view.FxmlView;

import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/**
 * 
 * @author shíQíang㊚
 *
 */
public class TakeFace implements Runnable{
		
	private LinkedBlockingQueue<BufferedImage> takeQueue;//阻塞队列
	private WebCamPreviewController webCam;
	private UserFaceInfoService userFaceInfoService;
	public TakeFace(LinkedBlockingQueue<BufferedImage> takeQueue ,WebCamPreviewController webCam,
			UserFaceInfoService userFaceInfoService){
		this.takeQueue = takeQueue; 
		this.webCam = webCam;
		this.userFaceInfoService = userFaceInfoService;
	}
	
	@Override
	public void run(){
		try {
			while(ExcutorUtil.isTakeRunning){
				BufferedImage data = takeQueue.poll(2, TimeUnit.SECONDS);//有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
                if (null != data){
                    //System.out.println("人脸拍照拿到数据");
                    WritableImage hasCheckedFace = SwingFXUtils.toFXImage(data, null);
     				if (ExcutorUtil.toTakePicture && hasCheckedFace != null){
     					ExcutorUtil.toTakePicture = false; 
     					showPicture(hasCheckedFace); 
     				} 
     				data.flush();
                }else{
                	//System.out.println("无人脸拍照数据...");
                }
			}
			
		} catch (Exception e){ 
			e.printStackTrace();
		}
	}
	
	protected void showPicture(Image image){
		Platform.runLater(new Runnable(){ 
			@Override
			public void run(){
				
				FXMLLoader loader = new FXMLLoader(getClass().getResource(FxmlView.TAKE.getFxmlFile()));
				Stage stage = new Stage();
				loader.setController(new TakeFaceController(image, userFaceInfoService));
		
				try {
					
					stage.setScene(new Scene(loader.load()));
					stage.setTitle(FxmlView.TAKE.getTitle());
					stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
						@Override
						public void handle(WindowEvent event){ 
							webCam.search();
						}
					});
					stage.show();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
		}); 
	}	
}